import React, { useEffect, useContext } from 'react';
import {
  LockOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProConfigProvider,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import md5 from "js-md5"
import useUserStore from '@/store/modules/user';
import { useNavigate } from 'react-router-dom';
import { isUndefined } from 'lodash';
import { MenuContext } from '@/router/menuContext'
import {ssoLoginTs} from "@/api/login/ssoLogin";
import styles from './index.module.less'

type FormData = { rememberMe?: boolean; username: string; password: string; }

const initData = {
  username: "",
  password: "",
  rememberMe: false,
}
//dev
// const SSO_SERVER_WEB_TS = "https://login.microsoftonline.com/7ba64ac2-8a2b-417e-9b8f-fcf8238f2a56/oauth2/v2.0/authorize?client_id=91a3070e-2db5-4f77-b47e-edd5fb14f5a0&response_type=code&scope=openid&redirect_uri=https://cpsrdev.kenvue.com/index"
//qa 
// const SSO_SERVER_WEB_TS = "https://login.microsoftonline.com/7ba64ac2-8a2b-417e-9b8f-fcf8238f2a56/oauth2/v2.0/authorize?client_id=6017e89b-3d90-467e-a73d-84e5335ec67a&response_type=code&scope=openid&redirect_uri=https://cpsrqa.kenvue.com/index"
//prod rrd
const SSO_SERVER_WEB_TS='https://login.microsoftonline.com/7ba64ac2-8a2b-417e-9b8f-fcf8238f2a56/oauth2/v2.0/authorize?client_id=1f7db451-f2cb-4aef-973b-be78266c12b1&response_type=code&scope=openid&redirect_uri=https://cpsrrnd.kenvue.com/index'


const getQueryVariable=(variable)=> {
  let url = decodeURIComponent(window.location.search)
  let query = url.substring(1);
  console.log(query,'query')
  let vars = query.split("?");
  for (let i = 0; i < vars.length; i++) {
      let pair = vars[i].split("=");
      if (pair[0] == variable) { return pair[1]; }
  }
  return (false);
}

const getInitData = () => {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  return {
    username: isUndefined(username) ? initData.username : username,
    password: isUndefined(password) ? initData.password : decrypt(password),
    rememberMe: isUndefined(rememberMe) ? initData.rememberMe : Boolean(rememberMe)
  }
}


const Login = () => {
  const userStore = useUserStore();
  const navigate = useNavigate();
  const { reload } = useContext(MenuContext);

  useEffect(()=>{
    SSO()
  },[])

  const SSO = ()=>{
    let code = getQueryVariable("code")
    if(code){
      //用授权码，向自己后台进行请求登录
      ssoLoginTs(code).then((res) => {
          console.log(res,'codedata')
          // setToken(res.data.token)
          // setAccessToken(res.data.accessToken)
          navigate("/");
      }).catch(() => {
          console.log("异常发生")
          //授权码可能过期,验证异常，再去统一登录页面获取一次性使用的授权码
          window.location.href = SSO_SERVER_WEB_TS
      });
  
  }else{
      window.location.href = SSO_SERVER_WEB_TS
  }
  }

  const onFinish = async (values: FormData) => {
    const data = { ...values }
    if (values.rememberMe) {
      Cookies.set("username", values.username, { expires: 30 });
      Cookies.set("password", encrypt(values.password), { expires: 30 });
      Cookies.set("rememberMe", String(values.rememberMe), { expires: 30 });
    } else {
      // 否则移除
      Cookies.remove("username");
      Cookies.remove("password");
      Cookies.remove("rememberMe");
    }
    // 调用action的登录方法
    data.password = md5(values.password)
    const res = await userStore.login(data)
    if (res.success) {
      navigate("/");
      reload(true)
    };
  }

  return (
    <div className={styles.login}>
      <div className={styles.warp}>
       {/* <ProConfigProvider hashed={false}>
          <div className={styles.title}>安全评估系统</div>
          <LoginForm
            onFinish={onFinish}
            request={async () => getInitData()}
            autoFocusFirstInput
          >
            <ProFormText
              name="username"
              fieldProps={{ size: 'large', prefix: <UserOutlined className={'prefixIcon'} /> }}
              placeholder={'账号'}
              rules={[
                {
                  required: true,
                  message: '请输入您的账号!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{ size: 'large', prefix: <LockOutlined className={'prefixIcon'} /> }}
              placeholder={'密码'}
              rules={[
                {
                  required: true,
                  message: '请输入您的密码！',
                },
              ]}
            />
            <div className={styles.item}>
              <ProFormCheckbox noStyle name="rememberMe">自动登录</ProFormCheckbox>
            </div>
          </LoginForm>
        </ProConfigProvider>   */}
         
      </div>
    </div>
  )
}

export default Login